package com.kupdater.util;

import com.sun.org.apache.bcel.internal.generic.ClassGen;
import com.sun.org.apache.bcel.internal.classfile.ClassParser;

import java.io.*;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;


/**
 * Created by IntelliJ IDEA.
 * User: Jan Ove
 * Date: 29.jan.2009
 * Time: 19:32:46
 * To change this template use File | Settings | File Templates.
 */
public class JARAdapter {
	public ClassGen[] loadClasses(String jarName) {
		try {
			LinkedList<ClassGen> classes = new LinkedList<ClassGen>();
			JarFile file = new JarFile(jarName);
			Enumeration<JarEntry> entries = file.entries();
			while(entries.hasMoreElements()) {
				JarEntry entry = entries.nextElement();
				if(entry.getName().endsWith(".class")) {
                    ClassGen cG = new ClassGen(new ClassParser(file.getInputStream(entry), entry.getName().replaceAll(".class", "")).parse());
					classes.add(cG);
				}
			}
			return classes.toArray(new ClassGen[0]);
		} catch(IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public void dumpClasses(String jarName, ClassGen[] classes) {
		try {
			File file = new File(jarName);
			JarOutputStream out = new JarOutputStream(new FileOutputStream(file));
			for(ClassGen cG : classes) {
				JarEntry entry = new JarEntry(cG.getClassName() + ".class");
				out.putNextEntry(entry);
                byte[] b = cG.getJavaClass().getBytes();
				out.write(b);
			}
			out.close();
		} catch(IOException e) {
			e.printStackTrace();
		}
	}
}

